<!-- 没有渐变 -->
<script setup>
import { ref, reactive, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { sensorByIdData, sensorByIdDvalue, sensorByIdDiff } from "@T2/service/api.ts";
import * as echarts from 'echarts';
import vueECharts from "vue-echarts";
import dayjs from 'dayjs';
const props = defineProps({
  params: {
    type: Array,
    required: true,
  },
  currentDex: {
    type: Number,
    default: 0,
  },
  updateTimes: {
    type: Number,
    default: 0,
  },
  showDatePicker: {
    type: Boolean,
    default: true,
  },
});

const datePicker = reactive({
  type: 'date',
	dft: dayjs(dayjs(), 'YYYY-MM-DD'),
  current: dayjs().format('YYYY-MM-DD'),
	text: '',
});
const typeToText = {
	date: ['日期: ', 'YYYY-MM-DD'],
	month: ['月份: ', 'YYYY-MM'],
	year: ['年份: ', 'YYYY'],
};
watch(() => [datePicker.type, datePicker.current], (nv, ov) => {
	datePicker.dft = dayjs(datePicker.current, typeToText[datePicker.type][1]);
});
function dateChange(date, str) {
  datePicker.current = str;
	beforeGetData();
}
const chartRef = ref(null);
watch(() => props.updateTimes, (nv, ov) => {
	beforeGetData();
});
watch(() => props.currentDex, (nv, ov) => {
  updateDatePicker(props.params[0].t)
	beforeGetData();
});
onMounted(() => {
  updateDatePicker(props.params[0].t)
  beforeGetData();
});
function updateDatePicker(t) {
  if (t === 'c' || t === 'ch') {
  	datePicker.type = 'date';
    datePicker.current = dayjs(datePicker.current).format('YYYY-MM-DD');
  } else if (t === 'cd') {
  	datePicker.type = 'month';
    datePicker.current = dayjs(datePicker.current).format('YYYY-MM');
  } else if (t === 'cm') {
  	datePicker.type = 'year';
    datePicker.current = dayjs(datePicker.current).format('YYYY');
  }
}
const option = {
  animation: false,										  	  //默认，是否开启动画
  backgroundColor: 'rgba(0, 18, 24, 0)',    //默认，无背景颜色
  color: ["#0082D9", "#C9FFFF", "#0FF6F0", "#7585A2"],
  dataset: [],                              //默认，数据集
  series: [],                               //默认，系列
  tooltip: {
    trigger: 'axis',                        //默认，axis坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用。
    backgroundColor: 'rgba(0,28,32,0.96)',  //提示框背景颜色
    borderColor: 'rgba(23,178,178,0.6)',    //提示框边框颜色
    textStyle: {
      color: '#D3F2EE',                     //提示框字体颜色
      fontSize: 14,                         //提示框字体大小
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 500,
    },
  },
  legend: {
    icon: 'rect',                        //默认，图例icon
    bottom: 0,                           //图例距容器顶部距离
    itemWidth: 6,                        //图例图形宽度
    itemHeight: 6,                       //图例图形高度
    textStyle: {
    	color: '#B2B2B2',                  //图例文字颜色
    	fontSize: 12,                      //图例文字大小
    },
  },
  grid: {
    containLabel: true,                   //默认，为true表示外边 距离 包含刻度标签在内的整个图表
    bottom: 25,                           //默认，网格离容器底部距离
    right: '2.5%',                        //默认，网格离容器右侧距离
    left: '2.5%',                         //默认，网格离容器左侧距离
    top: 12,                              //网格离容器顶部距离
  },
  xAxis: {
    boundaryGap: false,                   //默认， boundaryGap值为false的时候，折线第一个点在y轴上
    type: 'time',                         //默认，时间轴
    splitLine: {
      show: true,
      lineStyle: {
        color: 'rgba(92,204,197,0.24)',
        type: [3, 3],
      }
    },
    axisLine: {
      lineStyle: {
        width: 2,
        color: '#0a2a2d',
      }
    },
    axisTick: {
      show: false,
    },
    axisLabel: {
      color: '#5CCCC5',
      fontSize: 12,
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 400,
      width: 48,
      interval:0,
      overflow: 'break',
    },
  },
  yAxis: {
    type: 'value',                        //默认，数值轴
    splitLine: {
      lineStyle: {
        color: 'rgba(92,204,197,0.24)',
        type: [3, 3],
      }
    },
    axisLabel: {
      color: '#5CCCC5',
      fontFamily: 'PingFangSC, PingFang SC',
      fontWeight: 400,
      lineHeight: 16,
      fontSize: 12,                       //刻度标签字体大小
    },
    nameTextStyle: {
      color: "#5CCCC5",                   //坐标轴名称字体颜色
      fontSize: 10,                       //坐标轴名称字体大小
    },
  },
}
let yMax = 0, unitCg = 'first', seriesInfo = [];
function beforeGetData() {
  option.dataset = [];
  option.series = [];
  yMax = 0;
  unitCg = 'first';
  seriesInfo = [];
  props.params?.forEach((params, index) => {
    if (params.t === "c") {
      getCurLine(params);
    } else if (params.t === "ch") {
      getHourLine(params);
    } else if (params.t === "cd") {
      getDayLine(params);
    } else if (params.t === "cm") {
      getMonthBar(params);
    }
  });
}
function getCurLine(params) {
	params.s && sensorByIdData({
		method: "get",
		id: params.s,
		params: {
			page: 1,
      ordering: 'create_time',
			pagesize: 1000,
			start: dayjs(datePicker.current).format('YYYY-MM-DD') + " 00:00:00",
      end: dayjs(datePicker.current).format('YYYY-MM-DD') + " 23:59:59",
		},
	}).then((res) => {
		let { results, unit, map } = res;
    let source = [];
    if (map) {
      let mapNew = {};
      for (let key in map) {
        let value = map[key];
        if (value) {
          [value, key] = [key, value];
          mapNew[key] = +value;
        }
      }
      let stepH = Object.keys(mapNew).length;
      seriesInfo.push({
        stepH: stepH,
      });
      results.forEach(item => {
      	item.data = item.data;
        source.push([item.create_time, item.data, mapNew[item.data], mapNew[item.data]]);
      });
      option.dataset.push({
        dimensions: ['time', 'data', 'mapData', 'tarData'],
        source,
      });
      const len = option.dataset.length - 1;
      option.series.push({
      	name: params.n,
      	type: "line",
      	showSymbol: false,
      	lineStyle: {
      		width: 1,
      	},
        itemStyle: {
          color: params.o,
        },
        datasetIndex: len,
        encode: { x: 'time', y: 'tarData' },
        step: 'end',
      });
    } else {
      results.forEach(item => {
      	item.data = +item.data;
      	if (item.data > yMax) {
          yMax = item.data;
        }
        source.push([item.create_time, item.data, (item.data / 10000).toFixed(2)]);
      });
      option.dataset.push({
        dimensions: ['time', 'data', 'miniData'],
        source,
      });
      seriesInfo.push({
        unit: unit,
        oriUnit: unit,
      });
      const len = option.dataset.length - 1;
      option.series.push({
      	name: params.n,
      	type: "line",
      	showSymbol: false,
      	lineStyle: {
      		width: 1,
      	},
        itemStyle: {
          color: params.o,
        },
        datasetIndex: len,
      });
      encodeCheck(unit, params);
    }
    if (unitCg !== 'first') {
      let ym = 0;
      if (unitCg === 'error' || yMax <= 10000) {
        ym = yMax;
      } else {
        ym = yMax / 10000;
      }
      option.series.forEach((i, dex) => {
        if (i.step) {
          const mulp = getMulPower(seriesInfo[dex].stepH, ym);
          const sub = option.dataset[dex].dimensions.indexOf(i.encode.y);
          const _sub = option.dataset[dex].dimensions.indexOf('mapData');
          option.dataset[dex].source.forEach(j => {
            j[sub] = j[_sub] * mulp;
          });
        }
      });
    }
    // option.xAxis.min = dayjs(datePicker.current).format('YYYY-MM-DD') + " 00:00:00";
    // option.xAxis.max = dayjs(datePicker.current).format('YYYY-MM-DD') + " 23:59:59";
    if (source.length > 4) {
      option.xAxis.splitNumber = 4;
    } else {
      option.xAxis.splitNumber = source.length;
    }
    option.xAxis.axisLabel.formatter = function (value) {
    	return dayjs(value).format('HH:mm');
    };
    option.tooltip.formatter = function(par) {
    	let time = par.length && dayjs(par[0].data[0]).format("YYYY-MM-DD HH:mm:ss");
    	let res = time + '<br/>';
    	par.forEach((ser, ind) => {
        let value = '', ut = '';
        if (option.series[ser.seriesIndex].step) {
          const _sub = ser.dimensionNames.indexOf('data');
          value = ser.data[_sub];
        } else if (seriesInfo.length > ser.seriesIndex) {
          value = ser.data[ser.encode.y] + '&nbsp;';
          ut = seriesInfo[ser.seriesIndex].unit;
        }
    		res = res
    			+ `<div style="display:flex;align-items:center;justify-content:space-between;margin-top:4px;">`
            + `<div style="display:flex;align-items:center;font-size:${option.tooltip.textStyle.fontSize}px;color:#B2B2B2">`
              + ser.marker
              + ser.seriesName
            + '</div>'
            + `<div style="display:flex;align-items:center;margin-left:15px;font-size:${option.tooltip.textStyle.fontSize}px">`
              + `<b style="font-size:${option.tooltip.textStyle.fontSize}px;font-family:YouSheBiaoTiHei">${value}</b>`
              + ut
            + '</div>'
          + '</div>'
    	});
    	return res;
    };
    chartRef.value.chart.setOption(option, true);
	})
}

function getHourLine(params) {
  params.s && sensorByIdDvalue({
  	method: "get",
  	id: params.s,
  	params: {
  		status: "每小时",
      ordering: 'create_time',
  		start: dayjs(datePicker.current).format('YYYY-MM-DD') + " 01:00:00",
  		end: dayjs(dayjs(datePicker.current).format('YYYY-MM-DD')).add(1, 'day').format("YYYY-MM-DD") + " 01:00:00",
  	},
  }).then(res => {
    let { results, unit, } = res;
    let source = [];
    results.forEach(item => {
    	item.data = +item.data;
    	if (item.data > yMax) {
        yMax = item.data;
      }
      source.push([
        dayjs(item.create_time).subtract(1, 'hour').format("YYYY-MM-DD HH") + ":00:00",
        item.data,
        (item.data / 10000).toFixed(2),
      ]);
    });
    option.dataset.push({
      dimensions: ['time', 'data', 'miniData'],
      source,
    });
    seriesInfo.push({
      unit: unit,
      oriUnit: unit,
    });
    option.series.push({
    	name: params.n,
    	type: "line",
    	showSymbol: true,       //不加这个会导致多系列时，只有一个系列显示了标记
    	symbolSize: 0,
    	lineStyle: {
    		width: 1,
    	},
      datasetIndex: option.dataset.length - 1,
    });
    encodeCheck(unit, params);
    // option.xAxis.min = dayjs(datePicker.current).format('YYYY-MM-DD') + " 00:00:00";
    // option.xAxis.max = dayjs(datePicker.current).format('YYYY-MM-DD') + " 23:59:59";
    if (source.length > 4) {
      option.xAxis.splitNumber = 4;
    } else {
      option.xAxis.splitNumber = source.length;
    }
    option.xAxis.axisLabel.formatter = function (value) {
    	return dayjs(value).format('HH:00');
    };
    option.tooltip.formatter = function(par) {
    	let time = par.length && dayjs(par[0].data[0]).format("YYYY-MM-DD HH时");
    	let res = time + '<br/>';
    	par.forEach(ser => {
        let ut = '';
        if (seriesInfo.length > ser.seriesIndex) {
          ut = seriesInfo[ser.seriesIndex].unit;
        }
    		res = res
    			+ `<div style="display:flex;align-items:center;justify-content:space-between;margin-top:4px;">`
            + `<div style="display:flex;align-items:center;font-size:${option.tooltip.textStyle.fontSize}px;color:#B2B2B2">`
              + ser.marker
              + ser.seriesName
            + '</div>'
            + `<div style="display:flex;align-items:center;margin-left:15px;font-size:${option.tooltip.textStyle.fontSize}px">`
              + `<b style="font-size:${option.tooltip.textStyle.fontSize}px;font-family:YouSheBiaoTiHei">${ser.data[ser.encode.y]}&nbsp;</b>`
              + ut
            + '</div>'
          + '</div>'
    	});
    	return res;
    };
    chartRef.value.chart.setOption(option, true);
  });
}

function getDayLine(params) {
  Promise.all([getDayDvalue(params), getIdDiff(params)]).then(res => {
    let { results, unit, } = res[0];
    let { today } = res[1];
    if (dayjs(datePicker.current).format('YYYY-MM') === dayjs().format('YYYY-MM')) {
      results.push({
        id: null,
        create_time: dayjs().add(1, 'day').format("YYYY-MM-DD") + " 00:01:00",
        data: today,
      });
    }
    let source = [];
    results.forEach(item => {
    	item.data = +item.data;
    	if (item.data > yMax) {
        yMax = item.data;
      }
      source.push([
        dayjs(item.create_time).subtract(1, 'day').format("YYYY-MM-DD") + " 00:00:00",
        item.data,
        (item.data / 10000).toFixed(2),
      ]);
    });
    option.dataset.push({
      dimensions: ['time', 'data', 'miniData'],
      source,
    });
    seriesInfo.push({
      unit: unit,
      oriUnit: unit,
    });
    option.series.push({
    	name: params.n,
    	type: "line",
    	showSymbol: true,       //不加这个会导致多系列时，只有一个系列显示了标记
    	symbolSize: 0,
    	lineStyle: {
    		width: 1,
    	},
      datasetIndex: option.dataset.length - 1,
    });
    encodeCheck(unit, params);
    // option.xAxis.min = dayjs(datePicker.current).format('YYYY-MM') + "-01 00:00:00";
    // option.xAxis.max = dayjs(dayjs(datePicker.current).format('YYYY-MM')).add(1, 'month').subtract(1, 'day').format("YYYY-MM-DD") + " 01:00:00";
    if (source.length > 4) {
      option.xAxis.splitNumber = 4;
    } else {
      option.xAxis.splitNumber = source.length;
    }
    option.xAxis.axisLabel.formatter = function (value) {
    	return dayjs(value).format('DD日');
    };
    option.tooltip.formatter = function(par) {
    	let time = par.length && dayjs(par[0].data[0]).format("DD日");
    	let res = time + '<br/>';
    	par.forEach(ser => {
        let ut = '';
        if (seriesInfo.length > ser.seriesIndex) {
          ut = seriesInfo[ser.seriesIndex].unit;
        }
    		res = res
    			+ `<div style="display:flex;align-items:center;justify-content:space-between;margin-top:4px;">`
            + `<div style="display:flex;align-items:center;font-size:${option.tooltip.textStyle.fontSize}px;color:#B2B2B2">`
              + ser.marker
              + ser.seriesName
            + '</div>'
            + `<div style="display:flex;align-items:center;margin-left:15px;font-size:${option.tooltip.textStyle.fontSize}px">`
              + `<b style="font-size:${option.tooltip.textStyle.fontSize}px;font-family:YouSheBiaoTiHei">${ser.data[ser.encode.y]}&nbsp;</b>`
              + ut
            + '</div>'
          + '</div>'
    	});
    	return res;
    };
    chartRef.value.chart.setOption(option, true);
  });
}

function getDayDvalue(params) {
	return new Promise((resolve, reject) => {
		params.s && sensorByIdDvalue({
			method: "get",
			id: params.s,
			params: {
				status: "每日",
        ordering: 'create_time',
				start: dayjs(datePicker.current).format("YYYY-MM") + "-02 00:00:00",
				end: dayjs(dayjs(datePicker.current).format('YYYY-MM')).add(1, 'month').format("YYYY-MM") + "-02 00:00:00",
			},
		}).then(res => {
			resolve(res);
		}).catch(e => {
			reject(e);
		});
	});
}

function getMonthBar(params) {
  Promise.all([getMonthDvalue(params), getIdDiff(params)]).then(res => {
    let { results, unit, } = res[0];
    let { month } = res[1];
    if (dayjs(datePicker.current).format('YYYY') === dayjs().format('YYYY')) {
      results.push({
        id: null,
        create_time: dayjs().add(1, 'month').format("YYYY-MM") + "-01 00:01:00",
        data: month,
      });
    }
    let source = [];
    results.forEach(item => {
    	item.data = +item.data;
    	if (item.data > yMax) {
        yMax = item.data;
      }
      source.push([
        dayjs(item.create_time).subtract(1, 'month').format("YYYY-MM") + "-01 00:00:00",
        item.data,
        (item.data / 10000).toFixed(2),
      ]);
    });
    option.dataset.push({
      dimensions: ['time', 'data', 'miniData'],
      source,
    });
    seriesInfo.push({
      unit: unit,
      oriUnit: unit,
    });
    option.series.push({
    	name: params.n,
    	type: "bar",
    	barWidth: 6,
      datasetIndex: option.dataset.length - 1,
    });
    encodeCheck(unit, params);
    // option.xAxis.min = dayjs(datePicker.current).format('YYYY') + "-01-01 00:00:00";
    // option.xAxis.max = dayjs(dayjs(datePicker.current).format('YYYY')).add(1, 'year').subtract(1, 'month').format("YYYY-MM") + "-02 00:00:00";
    if (source.length > 4) {
      option.xAxis.splitNumber = 4;
    } else {
      option.xAxis.splitNumber = source.length;
    }
    option.xAxis.axisLabel.formatter = function (value) {
    	return dayjs(value).format('MM月');
    };
    option.tooltip.formatter = function(par) {
    	let time = par.length && dayjs(par[0].data[0]).format("MM月");
    	let res = time + '<br/>';
    	par.forEach(ser => {
        let ut = '';
        if (seriesInfo.length > ser.seriesIndex) {
          ut = seriesInfo[ser.seriesIndex].unit;
        }
    		res = res
    			+ `<div style="display:flex;align-items:center;justify-content:space-between;margin-top:4px;">`
            + `<div style="display:flex;align-items:center;font-size:${option.tooltip.textStyle.fontSize}px;color:#B2B2B2">`
              + ser.marker
              + ser.seriesName
            + '</div>'
            + `<div style="display:flex;align-items:center;margin-left:15px;font-size:${option.tooltip.textStyle.fontSize}px">`
              + `<b style="font-size:${option.tooltip.textStyle.fontSize}px;font-family:YouSheBiaoTiHei">${ser.data[ser.encode.y]}&nbsp;</b>`
              + ut
            + '</div>'
          + '</div>'
    	});
    	return res;
    };
    chartRef.value.chart.setOption(option, true);
  });
}

function getMonthDvalue(params) {
	return new Promise((resolve, reject) => {
		params.s && sensorByIdDvalue({
			method: "get",
			id: params.s,
			params: {
				status: "每月",
        ordering: 'create_time',
				start: dayjs(datePicker.current).format("YYYY") + "-02-01 00:00:00",
				end: dayjs(dayjs(datePicker.current).format('YYYY')).add(1, 'year').format("YYYY") + "-02-01 00:00:00",
			},
		}).then(res => {
			resolve(res);
		}).catch(e => {
			reject(e);
		});
	});
}

function getIdDiff(params) {
	return new Promise((resolve, reject) => {
		params.s && sensorByIdDiff({
			method: "get",
			id: params.s,
			params: {},
		}).then(res => {
			resolve(res);
		}).catch(e => {
			reject(e);
		});
	});
}

function getMulPower(len = 1, max = 0) {
  if (len === 0) {
    return 1;
  } else {
    const consult = max / (len - 1) / 2;
    const exp = consult.toExponential().split('e');
    const x = +exp[0];
    const y = +exp[1];
    return +(x * 10 ** y).toFixed(1);
  }
}

function dValueCommon(source, unit, params, type = 'line') {
  const len = option.dataset.length - 1;
  let obj = {};
  if (type === 'line') {
    obj = {
      type: "line",
      showSymbol: true,       //不加这个会导致多系列时，只有一个系列显示了标记
      symbolSize: 0,
      lineStyle: {
      	width: 1,
      },
    };
  } else if (type === 'bar'){
    obj = {
      type: "bar",
      barWidth: 6,
    };
  }
  option.series.push({
  	name: params.n,
  	...obj,
    datasetIndex: len,
  });
  encodeCheck(unit, params);
}

function encodeCheck(unit, params) {
  if (unitCg === 'first' || unitCg === unit) {
    if (unitCg === 'first') {
      unitCg = unit;
    }
    if (yMax > 10000) {
      option.yAxis.name = '万' + unit;
      option.series.forEach(i => {
        if (!i.step) {
          i.encode = { x: 'time', y: 'miniData' }
        }
      });
      seriesInfo.forEach(i => {
        if (!i.step) {
          i.unit = '万' + i.oriUnit;
        }
      });
    } else {
      option.yAxis.name = unit;
      option.series.forEach(i => {
        if (!i.step) {
          i.encode = { x: 'time', y: 'data' }
        }
      });
    }
  } else {
    unitCg = 'error';
    option.yAxis.name = '';
    option.series.forEach(i => {
      if (!i.step) {
        i.encode = { x: 'time', y: 'data' }
      }
    });
  }
}
</script>

<template>
  <div class="compBox">
    <a-date-picker
      size="small"
      dropdownClassName="aDatePickerDropdownClass"
      v-model:value="datePicker.dft"
      :disabledDate="(current) => current && current > dayjs().endOf('day')"
      :picker="datePicker.type"
      @change="dateChange"
      v-if="props.showDatePicker"
    />
    <div class="chartsBox">
      <vueECharts ref="chartRef" autoresize :option="option" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.compBox {
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.chartsBox {
  width: 100%;
  height: 230px;
}
:deep(.ant-picker.ant-picker-small) {
  border: 1px solid rgba(23,178,178,0.66) !important;
  border-radius: 2px;
  width: 105px;
  height: 20px;
  padding: 0 7px;
  .ant-picker-input>input {
    font-size: 12px;
    color: #84D9D0;
  }
  .ant-picker-suffix {
    display: flex;
  }
  .anticon.anticon-calendar>svg {
    color: #84D9D0 !important;
    width: 14px !important;
    height: 14px !important;
  }
}
</style>